<template>
  <div class="score-import">
    <!-- 导入按钮 -->
    <el-upload
      class="import-button"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
    >
      <el-button type="success">
        <el-icon><Upload /></el-icon> 批量导入
      </el-button>
    </el-upload>
    
    <!-- 导入对话框 -->
    <el-dialog
      title="批量导入成绩"
      v-model="importDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          description="请上传Excel文件，文件格式要求：学号、姓名、课程名称、成绩等列。支持.xlsx和.xls格式。"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <el-upload
          ref="uploadRef"
          drag
          action="#"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="handleFileSelect"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          accept=".xlsx,.xls"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传xlsx/xls文件，且不超过10MB
            </div>
          </template>
        </el-upload>
        
        <!-- 导入预览表格 -->
        <div v-if="previewData.length > 0" class="preview-section">
          <h4>数据预览（前5行）</h4>
          <el-table :data="previewData" border style="width: 100%">
            <el-table-column
              v-for="column in previewColumns"
              :key="column"
              :prop="column"
              :label="column"
              min-width="100"
            />
          </el-table>
        </div>
        
        <!-- 映射配置 -->
        <div v-if="previewData.length > 0" class="mapping-section">
          <h4>字段映射</h4>
          <el-form label-width="120px">
            <el-form-item label="学号列">
              <el-select v-model="fieldMapping.studentNumber" placeholder="选择学号列">
                <el-option v-for="col in previewColumns" :key="col" :label="col" :value="col" />
              </el-select>
            </el-form-item>
            <el-form-item label="姓名列">
              <el-select v-model="fieldMapping.studentName" placeholder="选择姓名列">
                <el-option v-for="col in previewColumns" :key="col" :label="col" :value="col" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程列">
              <el-select v-model="fieldMapping.courseName" placeholder="选择课程列">
                <el-option v-for="col in previewColumns" :key="col" :label="col" :value="col" />
              </el-select>
            </el-form-item>
            <el-form-item label="成绩列">
              <el-select v-model="fieldMapping.score" placeholder="选择成绩列">
                <el-option v-for="col in previewColumns" :key="col" :label="col" :value="col" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleImport"
          :loading="importing"
          :disabled="!canImport"
        >
          确定导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Upload, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

const emit = defineEmits(['import-success'])

const importDialogVisible = ref(false)
const importing = ref(false)
const fileList = ref([])
const previewData = ref([])
const previewColumns = ref([])
const uploadRef = ref()

const fieldMapping = ref({
  studentNumber: '',
  studentName: '',
  courseName: '',
  score: ''
})

const canImport = computed(() => {
  return previewData.value.length > 0 &&
         fieldMapping.value.studentNumber &&
         fieldMapping.value.studentName &&
         fieldMapping.value.courseName &&
         fieldMapping.value.score
})

const handleFileChange = () => {
  importDialogVisible.value = true
}

const handleFileSelect = (file) => {
  fileList.value = [file]
  parseExcelFile(file.raw)
}

const handleFileRemove = () => {
  fileList.value = []
  previewData.value = []
  previewColumns.value = []
  resetFieldMapping()
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

const parseExcelFile = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
      
      if (jsonData.length === 0) {
        ElMessage.error('Excel文件为空!')
        return
      }
      
      // 第一行作为列名
      const headers = jsonData[0]
      previewColumns.value = headers
      
      // 前5行数据作为预览
      const preview = jsonData.slice(1, 6).map(row => {
        const obj = {}
        headers.forEach((header, index) => {
          obj[header] = row[index] || ''
        })
        return obj
      })
      
      previewData.value = preview
      autoMapFields(headers)
      
    } catch (error) {
      ElMessage.error('解析Excel文件失败: ' + error.message)
    }
  }
  reader.readAsArrayBuffer(file)
}

const autoMapFields = (headers) => {
  // 自动匹配字段
  headers.forEach(header => {
    const lowerHeader = header.toLowerCase()
    if (lowerHeader.includes('学号') || lowerHeader.includes('studentnumber')) {
      fieldMapping.value.studentNumber = header
    } else if (lowerHeader.includes('姓名') || lowerHeader.includes('name')) {
      fieldMapping.value.studentName = header
    } else if (lowerHeader.includes('课程') || lowerHeader.includes('course')) {
      fieldMapping.value.courseName = header
    } else if (lowerHeader.includes('成绩') || lowerHeader.includes('score')) {
      fieldMapping.value.score = header
    }
  })
}

const resetFieldMapping = () => {
  fieldMapping.value = {
    studentNumber: '',
    studentName: '',
    courseName: '',
    score: ''
  }
}

const handleImport = async () => {
  if (!canImport.value) {
    ElMessage.warning('请完成字段映射配置')
    return
  }
  
  importing.value = true
  
  try {
    const file = fileList.value[0].raw
    const reader = new FileReader()
    
    reader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        
        const headers = jsonData[0]
        const importData = jsonData.slice(1).map(row => {
          const obj = {}
          obj.studentNumber = row[headers.indexOf(fieldMapping.value.studentNumber)]
          obj.studentName = row[headers.indexOf(fieldMapping.value.studentName)]
          obj.courseName = row[headers.indexOf(fieldMapping.value.courseName)]
          obj.score = parseFloat(row[headers.indexOf(fieldMapping.value.score)])
          return obj
        }).filter(item => item.studentNumber && item.studentName) // 过滤空行
        
        emit('import-success', importData)
        importDialogVisible.value = false
        resetImportState()
        ElMessage.success(`成功导入 ${importData.length} 条记录`)
        
      } catch (error) {
        ElMessage.error('导入失败: ' + error.message)
      } finally {
        importing.value = false
      }
    }
    
    reader.readAsArrayBuffer(file)
    
  } catch (error) {
    ElMessage.error('导入失败: ' + error.message)
    importing.value = false
  }
}

const resetImportState = () => {
  fileList.value = []
  previewData.value = []
  previewColumns.value = []
  resetFieldMapping()
}
</script>

<style scoped>
.score-import {
  display: inline-block;
}

.import-content {
  max-height: 600px;
  overflow-y: auto;
}

.preview-section,
.mapping-section {
  margin-top: 20px;
}

.preview-section h4,
.mapping-section h4 {
  color: #303133;
  margin-bottom: 10px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
}
</style>
